package algorithm.linklist;

class DoubleNode {
    int value;
    DoubleNode next;
    DoubleNode pre;

    public DoubleNode(int value) {
        this.value = value;
    }

    public DoubleNode revert() {
        DoubleNode head = this;
        DoubleNode next = null;
        DoubleNode pre = null;
        while (head != null) {
            next = head.next;   // 记录后面
            head.next = pre;    // 改后指针
            head.pre = next;    // 改前指针
            pre = head;         // pre后移
            head = next;        // node后移
        }
        return pre;
    }

    public static void main(String[] args) {
        DoubleNode node = getRandomNode(4, 100);
        printNodel(node);
        printNoder(node);
//        printNode(node.revert());
    }

    public static DoubleNode getRandomNode(int len, int maxVal) {
        int val = (int) (Math.random() * maxVal) + 1;
        System.out.println(val);
        DoubleNode doubleNode = new DoubleNode(val);
        len--;
        DoubleNode cur = null;
        while (len != 0) {
            if (doubleNode.next == null) {
                val = (int) (Math.random() * maxVal) + 1;
                System.out.println(val);
                doubleNode.next = new DoubleNode(val);
                cur = doubleNode.next;
                cur.pre = doubleNode;
            } else {
                val = (int) (Math.random() * maxVal) + 1;
                System.out.println(val);
                cur.next = new DoubleNode(val);
                cur.next.pre = cur;
                cur = cur.next;
            }
            len--;
        }
        return doubleNode;
    }

    private static void printNodel(DoubleNode node) {
        while (node != null) {
            System.out.print(node.value + " -> ");
            node = node.next;
        }
        System.out.println();
    }

    private static void printNoder(DoubleNode node) {
        while (node != null) {
            System.out.print(" <- " + node.value);
            node = node.next;
        }
        System.out.println();
    }

}

